package com.truthbean.jeetb.utils.web.invoker;

import com.truthbean.jeetb.utils.web.Utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class UnPackInvoker extends DefaultInvoker {
    public boolean doBefore() {
        return false;
    }

    public boolean doAfter() {
        return false;
    }

    public void invoke(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
        try {
            String savepath = request.getParameter("savepath");
            String zipfile = request.getParameter("zipfile");
            if (Utils.isEmpty(savepath) || Utils.isEmpty(zipfile))
                return;
            File save = new File(savepath);
            save.mkdirs();
            ZipFile file = new ZipFile(new File(zipfile));
            Enumeration e = file.entries();
            while (e.hasMoreElements()) {
                ZipEntry en = (ZipEntry) e.nextElement();
                String entryPath = en.getName();
                int index = entryPath.lastIndexOf("/");
                if (index != -1)
                    entryPath = entryPath.substring(0, index);
                File absEntryFile = new File(save, entryPath);
                if (!absEntryFile.exists() && (en.isDirectory() || en.getName().indexOf("/") != -1))
                    absEntryFile.mkdirs();
                BufferedOutputStream output = null;
                BufferedInputStream input = null;
                try {
                    output = new BufferedOutputStream(
                            new FileOutputStream(new File(save, en.getName())));
                    input = new BufferedInputStream(
                            file.getInputStream(en));
                    byte[] b = new byte[1024];
                    int len = input.read(b);
                    while (len != -1) {
                        output.write(b, 0, len);
                        len = input.read(b);
                    }
                } catch (Exception ex) {
                } finally {
                    try {
                        if (output != null)
                            output.close();
                        if (input != null)
                            input.close();
                    } catch (Exception ex1) {
                    }
                }
            }
            file.close();
            session.setAttribute(MSG, "Unzip File Success!");
            response.sendRedirect(SHELL_NAME + "?o=index");
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}